package com.example.carrierapp.util;

import android.text.InputFilter;
import android.text.Spanned;

/**
 * 中文算2个字符，英文算一个字符
 * Created by lb on 2016/12/26.
 */

public class InputFilterUtils implements InputFilter {
    private int maxLen;

    public InputFilterUtils(int len) {
        maxLen=len;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        String newString=dest.toString()+source;
        if(getStringCharLenth(newString)>maxLen)
        {
            return "";
        }else
        {
            return source.toString();
        }
    }

    public static int getStringCharLenth(String str)
    {
        int charLen=0;
        char[] array = str.toCharArray();
        for (char anArray : array) {
            if ((char) (byte) anArray != anArray) {
                charLen = charLen + 2;
            } else {
                charLen++;
            }
        }
        return charLen;
    }
}
